<template>
<panel-head :route="route" />
  <div class="btns">
    <el-button icon="Plus" type="primary" @click="open(null)" size="small">新增</el-button>
  </div>
  <el-table :data="tableData.list" style="width: 100%">
    <el-table-column prop="id" label="id" />
    <el-table-column prop="name" label="昵称" />
    <el-table-column prop="permissionName" label="菜单权限" width="500px" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button type="primary" @click="open(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="pagination-info">
    <el-pagination
      v-model:current-page="paginationData.pageNum"
      :page-size="paginationData.pageSize"
      :background="false"
      layout="total, prev, pager, next"
      :total="tableData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      size="small"
    />
  </div>
  <el-dialog
    v-model="dialogFormVisable"
    :before-close="beforeClose"
    title="添加权限"
    width="500"
  >
    <el-form
      ref="formRef"
      label-width="100px"
      label-position="left"
      :model="form"
      :rules="rules"
    >
      <el-form-item prop="id" v-show="false">
        <el-input v-model="form.id"
      /></el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请填写权限名称"
      /></el-form-item>
      <el-form-item label="权限" prop="permissions">
        <!-- 默认项的展开 -->
        <el-tree
          :data="permissionData"
          style="max-width: 600px"
          node-key="id"
          show-checkbox
          :default-checked-keys="defaultKeys"
          ref="treeRef"
          :default-expanded-keys="[2]"
      /></el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="promary" @click="confirm(formRef)">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import { userGetMenu, userSetMenu, menuList } from "@/api";
import { useRoute } from "vue-router";
const route = useRoute();
const formRef = ref(); //表单ref
const paginationData = reactive({
  //当前页码
  pageNum: 1,
  // 每页显示的数量
  pageSize: 10,
});
// 列表数据
const tableData = reactive({
  list: [],
  total: 0,
});
const handleSizeChange = (val) => {
  paginationData.pageSize = val;
  getListData();
};
const handleCurrentChange = (val) => {
  paginationData.pageNum = val;
  getListData();
};
// 表单校验
const rules = reactive({
  name: [
    // required: true 必填，message: 错误信息，trigger: 触发方式
    { required: true, message: "请输入权限名称", trigger: "blur" },
  ],
});
//表单提交
const confirm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //获取到选择的checkbox数据
      const permissions = JSON.stringify(treeRef.value.getCheckedKeys());
      userSetMenu({ name: form.name, permissions, id: form.id }).then(
        ({ data }) => {
          //  关闭弹窗
          beforeClose();
          // 重新请求列表数据
          getListData();
        }
      );
    } else {
      console.log("error submit!!", fields);
    }
  });
};
//选中权限
const defaultKeys = [4, 5];
const treeRef = ref();
// 打开弹窗
// 因为复用同一个弹窗逻辑
// 如果调用 open 函数时没有传递参数，或者传递的参数是 undefined ， rowData 会被默认设置为空对象 {} 。
const open = (rowData = {}) => {
  dialogFormVisable.value = true; // 打开弹窗
  //弹窗打开form生成是异步的
  // 使用 nextTick 确保在 DOM 更新完成后执行回调函数
  nextTick(() => {
    if (rowData) {
      Object.assign(form, { id: rowData.id, name: rowData.name });
      treeRef.value.setCheckedKeys(JSON.parse(rowData.permissions));
    }
  });
};
//树形菜单权限数据
const permissionData = ref([]);
// form的数据
const form = reactive({
  id: "", //编辑时需要id
  name: "",
  permissions: "",
});
const dialogFormVisable = ref(false);
//关闭弹窗的回调
const beforeClose = () => {
  dialogFormVisable.value = false; // 关闭弹窗
  // 清空表单数据
  formRef.value.resetFields(); // 清空表单数据
  // 清空树形菜单数据
  treeRef.value.setCheckedKeys(defaultKeys); // 清空树形菜单数据
};
//请求列表数据
const getListData = async () => {
  await menuList(paginationData).then(({ data }) => {
    console.log("list", data);
    const { list, total } = data.data;
    tableData.list = list;
    tableData.total = total;
  });
};
onMounted(() => {
  //菜单数据
  userGetMenu().then(({ data }) => {
    // console.log(data);
    permissionData.value = data.data;
  });
  getListData();
});
</script>

<style scoped lang="less">
.btns {
  padding: 10px 0 10px 10px;
  background-color: #fff;
}
</style>
